package com.ja.openchat.viewmodels;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.SplashActivity;
import com.ja.openchat.ui.me.AboutFragment;
import com.ja.openchat.ui.me.AccountSecurityActivity;
import com.ja.openchat.ui.me.CommonSetFragment;
import com.ja.openchat.ui.me.DataStorageFragment;
import com.ja.openchat.ui.me.NotificationSoundSetFragment;
import com.ja.openchat.ui.me.PersonalDataFragment;
import com.ja.openchat.ui.me.PrivaicyAndPermissionActivity;
import com.ja.openchat.ui.me.SetPwdFragment;
import com.ja.openchat.views.ChooseListDialog;
import com.ja.openchat.views.OnChooseListListener;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.UserMyInfo;
import com.zy.openchat.util.CacheDataManager;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.MultiLanguageUtil;


public class SetViewModel extends BaseViewModel {
    public ObservableField<String> pwdDes = new ObservableField<>("设置密码");
    public ObservableField<String> cacheValue = new ObservableField<>(CacheDataManager.getTotalCacheSize(getApplication()));
    public ObservableField<String> lanuageValue = new ObservableField<>(getLanguageLable());
    private boolean hasPassword = false;

    public SetViewModel(@NonNull Application application) {
        super(application);
    }

    //点击事件
    public BindingCommand btnOnClickCommand = new BindingCommand(() -> {
        ToastUtils.showShort("点击事件");
    });
    //通用设置点击事件
    public BindingCommand commonOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(CommonSetFragment.class.getCanonicalName());
    });
    //账号与安全点击事件
    public BindingCommand accountSecurityOnClickCommand = new BindingCommand(() -> {
        startActivity(AccountSecurityActivity.class);
    });
    //个人资料点击事件
    public BindingCommand personalDataOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(PersonalDataFragment.class.getCanonicalName());
    });
    //存储点击事件
    public BindingCommand dataStorageOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(DataStorageFragment.class.getCanonicalName());
    });
    //通知与声音点击事件
    public BindingCommand notificationSoundSetOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(NotificationSoundSetFragment.class.getCanonicalName());
    });
    //隐私权限点击事件
    public BindingCommand privacyRightsSetOnClickCommand = new BindingCommand(() -> {
        startActivity(PrivaicyAndPermissionActivity.class);
    });
    //设置密码点击事件
    public BindingCommand setPwdOnClickCommand = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putBoolean("hasPassword", hasPassword);
        startContainerActivity(SetPwdFragment.class.getCanonicalName(), bundle);
    });

    //关于我们按钮的点击事件
    public BindingCommand aboutOnClickCommand = new BindingCommand(() -> startContainerActivity(AboutFragment.class.getCanonicalName()));

    public String getLanguageLable(){
        int languageId = MultiLanguageUtil.getInstance().getLanguageId();
        int strResId;
        switch (languageId){
            case MultiLanguageUtil.LANGUAGE_CHINESE:
                strResId = R.string.language_chinese;
                break;
            case MultiLanguageUtil.LANGUAGE_ENGLISH:
                strResId = R.string.language_english;
                break;
            default:
                strResId = R.string.language_system;
                break;
        }
        return App.getInstanse().getString(strResId);
    }

    public BindingCommand languageClickCommand = new BindingCommand(() -> {
        showChooseLanguage();
    });

    private void showChooseLanguage(){
        Context context = ActivityUtils.getTopActivity();
        ChooseListDialog.showChooseListDialog(context
                , Arrays.asList(new String[]{context.getString(R.string.language_system)
                        ,context.getString(R.string.language_chinese)
                        ,context.getString(R.string.language_english)}), -1
                ,context.getString(R.string.language_text) ,new OnChooseListListener() {
            @Override
            public void onChoose(int position, String value) {
                int languageId;
                switch (position){
                    case 1:
                        languageId = MultiLanguageUtil.LANGUAGE_CHINESE;
                        break;
                    case 2:
                        languageId = MultiLanguageUtil.LANGUAGE_ENGLISH;
                        break;
                    default:
                        languageId = MultiLanguageUtil.LANGUAGE_SYSTEM;
                        break;
                }
                MultiLanguageUtil.getInstance().updateLanguage(languageId);
                lanuageValue.set(getLanguageLable());
                Activity activity = ActivityUtils.getTopActivity();
                ActivityUtils.finishAllActivities();
                if(activity!=null){
                    SplashActivity.start(activity);
                }else{
                    Intent intent = new Intent(getApplication(), SplashActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    getApplication().startActivity(intent);
                }
            }
        });
    }
    //清除缓存点击事件
    public BindingCommand cleanCacheBtnOnClickCommand = new BindingCommand(() -> {
        clearCache();
    });

    public void logout() {
        TelegramManager.getTelegramManager().registerDevice(getApplication(), "", new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                TelegramManager.getTelegramManager().logout();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });

    }

    public void requestInfoData() {
        TelegramManager.getTelegramManager().queryUserMyInfo(getApplication(), new TgResultBlock<UserMyInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserMyInfo obj) {
                if (obj != null) {
                    hasPassword = obj.hasPassword;
                    pwdDes.set(obj.hasPassword ? "修改密码" : "设置密码");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    public void clearCache() {
        showProgress();
        addSubscribe(Observable.timer(1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                KLog.d("清除缓存");
                hideProgress();
                CacheDataManager.clearAllCache(getApplication());
                cacheValue.set(CacheDataManager.getTotalCacheSize(getApplication()));
            }
        }));
    }


}
